import { getToken, removeToken, setToken,  } from '@/utils/auth'
import {login,getLoginInfo} from "@/api/login";
import router from '@/router';

const user = {
  state: {
    token: getToken(),
    id: sessionStorage.getItem("userId") || '',
    name: sessionStorage.getItem("userName") || "",
    avatar: sessionStorage.getItem("userAvatar") || '',
    roles: [],
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          setToken(res.Satoken)
          commit('SET_TOKEN', res.Satoken)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取登录用户的信息
    GetLoginInfo({ commit }) {
      return new Promise((resolve) => {
        getLoginInfo().then(res => {
          console.log("获取登录用户信息",res.data)
          commit('SET_ID',res.data.id)
          commit('SET_NAME',res.data.username)
          commit('SET_AVATAR',res.data.avatar)
          // 将登录用户信息保存到session中
          sessionStorage.setItem('userName',res.data.username);
          sessionStorage.setItem("userId",res.data.id);
          sessionStorage.setItem("userAvatar",res.data.avatar)
          resolve();
        }).catch(() => {
          router.push("/login").catch(()=>{})
        })
      })
    },
    // 退出登录
    LoginOut(){
      removeToken()
      sessionStorage.removeItem('userName');
      sessionStorage.removeItem("userId");
      sessionStorage.removeItem("userAvatar")
      user.state = {}
      // 返回登录页
      router.push("/login")
    }
  }
}

export default user
